import { createRouter, createWebHistory } from 'vue-router';
import { useLoginUserStore, useTabsViewStore } from '@/index';
import routes from './routes';

const whitePathList = ['/404'];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

router.beforeEach(async (to, _from) => {
  const { loginUser } = useLoginUserStore();
  const { isIncludeName, isIncludePath, removeByName } = useTabsViewStore();
  if (typeof to.meta.header === 'string') {
    document.title = to.meta.header;
  } else if (typeof to.meta.title === 'string') {
    document.title = to.meta.title || '上核检测';
  }
  if (to.path === '/login') {
    return true;
  } else if (loginUser.token === undefined || loginUser.token === null) {
    return { path: '/login' };
  } else if (to.fullPath.startsWith('/flowable/form')) {
    typeof to.name === 'string' &&
      isIncludeName(to.name) &&
      !isIncludePath(to.fullPath) &&
      removeByName(to.name);
  } else if (to.redirectedFrom !== undefined || whitePathList.includes(to.path)) {
    return true;
  } else if (to.path === '/home') {
    return true;
  } else if (!loginUser.menus?.includes(to.meta.title as string)) {
    return { name: 'NotFoundRe' };
  } else {
    return true;
  }
});

export default router;
